package ro.dandanciu.webgallery.services.email;

import org.apache.log4j.Logger;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class EmailSender {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(EmailSender.class);

	private static String smtpServer = "smtp.gmail.com";

	private static String myAddress = "ddanciuster@gmail.com";

	public static void send(EmailMessage message) {
		if (logger.isDebugEnabled()) {
			logger.debug("send(EmailMessage) - start");
		}

		try {
			java.security.Security
					.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			Properties props = System.getProperties();
			props.put("mail.smtp.host", smtpServer);
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.starttls.enable","true");
			props.put("mail.smtp.auth", "true");
			Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getDefaultInstance(props, auth);
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(myAddress));
			
			InternetAddress[] addressTo = new InternetAddress[message.getToAddresses().size()];
			int i = 0;
			for (String to : message.getToAddresses()) {
				addressTo[i++] = new InternetAddress(to);
			}
			
			msg.setRecipients(Message.RecipientType.TO, addressTo);
			msg.setSubject(message.getSubject());
			msg.setText(message.getBody());
			msg.setHeader("X-Mailer", "LOTONtechEmail");
			msg.setSentDate(new Date());
			Transport.send(msg);
			if (logger.isDebugEnabled()) {
				logger.debug("Email: " + message + " sent.");
			}
		} catch (Exception ex) {
			logger.error("send(EmailMessage)", ex);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("send(EmailMessage) - end");
		}
	}
	
	/**
	 * SimpleAuthenticator is used to do simple authentication when the SMTP
	 * server requires it.
	 */
	private static class SMTPAuthenticator extends javax.mail.Authenticator {
 
		public PasswordAuthentication getPasswordAuthentication() {
			String username = myAddress;
			String password = "anexonice";
			return new PasswordAuthentication(username, password);
		}
	}

}
